package com.djmw.mouse.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import com.djmw.mouse.entity.Company;
import com.djmw.mouse.entity.CompanyTrade;
import com.djmw.mouse.repository.CompanyDao;
import com.djmw.mouse.repository.CompanyTradeDao;

//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class CompanyService {

	@Autowired
	private CompanyDao companyDao;
	@Autowired
	private CompanyTradeDao companyTradeDao;

	public Company getCompany(Long id) {
		return companyDao.findOne(id);
	}

	@Transactional(readOnly = false)
	public void saveCompany(Company entity) {
		companyDao.save(entity);
	}

	@Transactional(readOnly = false)
	public void deleteCompany(Long id) {
		companyDao.delete(id);
	}

	public List<Company> getAllCompany() {
		return (List<Company>) companyDao.findAll();
	}

	public Page<Company> getCompany(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		Specification<Company> spec = buildSpecification(searchParams);

		return companyDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("name".equals(sortType)) {
			sort = new Sort(Direction.ASC, "name");
		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Company> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<Company> spec = DynamicSpecifications.bySearchFilter(filters.values(), Company.class);
		return spec;
	}

	@Transactional(readOnly = false)
	public void changeCompanyStatus(Long id, int status) {
		companyDao.changeStatus(id, status);
	}

	@Transactional(readOnly = false)
	public void deposit(Long id, Double amount) {
		companyTradeDao.save(new CompanyTrade(companyDao.findOne(id), new Date(), CompanyTrade.TYPE_DEPOSIT, amount));
		companyDao.deposit(id, amount);
	}
}
